package admin_role_menus

import (
	"encoding/json"
	"gitee.com/theegg/go-brick/app/service/app"
	"gitee.com/theegg/go-brick/app/service/help/credis"
	"github.com/go-redis/redis/v8"
	"time"
)

var AllRoleMenusCacheKey = "admin_role_menus_all"

// @title 刷新 all menus 缓存
// @description 刷新 all menus 缓存
func FlushAllCache() (bool, error) {
	oRedis := credis.New()
	_, errDel := oRedis.Del(AllRoleMenusCacheKey)
	if errDel != nil {
		return false, errDel
	}

	return true, nil
}

// @title 从缓存获取所有的的菜单
// @description 如果缓存不存在　则从数据库取
// @return map[int]AdminRoleMenus
func GetAllAdminRoleMenusFromCache() (map[int64]*AdminRoleMenus, error) {
	oRedis := credis.New()
	data, errGet := oRedis.Get(AllRoleMenusCacheKey)
	if errGet != nil {
		if errGet == redis.Nil {
			data, errDb := GetAllAdminRoleMenusFromDb()
			if errDb != nil {
				return nil, app.NewError(errDb)
			}

			jsonData, _ := json.Marshal(data)

			errSet := oRedis.Set(AllRoleMenusCacheKey, string(jsonData), 12*time.Hour)
			if errSet != nil {
				panic(errSet)
			}

			return data, nil
		}
		panic("Redis-" + errGet.Error())
	}

	var returnData map[int64]*AdminRoleMenus
	jsonErr := json.Unmarshal(data, &returnData)
	if jsonErr != nil {
		return nil, app.NewError(jsonErr)
	}

	return returnData, nil
}

// @title 从数据库获取所有的菜单数据
// @return map[int64]AdminRoleMenus
func GetAllAdminRoleMenusFromDb() (map[int64]*AdminRoleMenus, error) {
	roleMenus := make(map[int64]*AdminRoleMenus)
	err := app.Db().Find(&roleMenus)
	if err != nil {
		return nil, app.NewError(err)
	}

	return roleMenus, nil
}
